//
//  BaseViewController.m
//  LotteryClient
//
//  Created by SunYu on 14-2-5.
//  Copyright (c) 2014年 SunYu. All rights reserved.
//

#import "BaseViewController.h"

#import "NavigationBar.h"
#import "UIViewController+Custom.h"
#import "TabViewController.h"
#import "MMProgressHUD.h"
#import "TipView.h"
#import "ActionSheet.h"
#undef   kHandleDataDefaultMessage
#define  kHandleDataDefaultMessage @""

#undef   kHandleDataCompleteDefaultMessage
#define  kHandleDataCompleteDefaultMessage @"数据处理完成！"

#undef   kInternetConnectionError
#define  kInternetConnectionError @"网络连接不通,请检查网络!"


@interface BaseViewController ()
@property(nonatomic,strong,readwrite) NavigationBar *navigationBar;
@property(nonatomic,strong) TipView *progressTipView;
@property(nonatomic,strong) UIView *maskView;
@end

@implementation BaseViewController
DEF_STATIC_PROPERTY_INT(baseType, BaseTypeViewController)

#pragma mark -
#pragma mark - lifecircle

- (id)init
{
    self = [super init];
    if (self)
    {
        self.navigationBarHeight = kDefaultNavigationBarHeight;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(IOS_7_0))
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil
                           bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
        _identifier = [[NSString alloc] initWithFormat:@"identifier_%p",
                                                       self];

    }


    return self;
}


- (void)loadView
{
    [super loadView];
    BaseView *view = [[BaseView alloc] initWithFrame:self.view.frame];
    view.transform                  = self.view.transform;
    view.contentScaleFactor         = self.view.contentScaleFactor;
    view.multipleTouchEnabled       = self.view.isMultipleTouchEnabled;
    view.exclusiveTouch             = self.view.isExclusiveTouch;
    view.autoresizingMask           = self.view.autoresizingMask;
    view.clipsToBounds              = self.view.clipsToBounds;
    view.backgroundColor            = self.view.backgroundColor;
    view.alpha                      = self.view.alpha;
    view.opaque                     = self.view.isOpaque;
    view.clearsContextBeforeDrawing = self.view.clearsContextBeforeDrawing;
    view.hidden                     = self.view.isHidden;
    view.contentMode                = self.view.contentMode;
//    view.contentStretch             = self.view.contentStretch;
    view.delegate                   = self;
    self.view                       = view;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	self.firstAppear = YES;
    // Do any additional setup after loading the view.
	self.view.backgroundColor = [UIColor colorWithRed:246/255.0 green:249/255.0 blue:248.0/255 alpha:1];
    if (self.hasNavigationBar)
    {
        [self setupNavigationBar];
    }
	
	 [self.navigationController.navigationBar setTranslucent:NO];
	
	self.coverView = [[ActivityIndicatorCoverView alloc] initWithFrame:self.view.bounds
                                                                 title:@""
                                                             imageName:nil];
	[self.view addSubview:self.coverView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.maskView.alpha = 0.0;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.firstAppear = NO;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.maskView = nil;
}
#pragma mark -
#pragma mark - getter & setter

- (void)setHasNavigationBar:(BOOL)hasNavigationBar
{
    _navigationBarHeight = hasNavigationBar ? kDefaultNavigationBarHeight : 0;
    _hasNavigationBar    = hasNavigationBar;
    if (_navigationBar)
    {
        _navigationBar.hidden = !hasNavigationBar;
    }

}


- (UIBarButtonItem *)defaultBackButtonItem
{
    if (!_defaultBackButtonItem)
    {
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame = CGRectMake(0.0, 0.0, self.navigationBarHeight, self.navigationBarHeight);
        [backButton setImage:[UIImage imageNamed:@"navigationbar_back_icon"]
                    forState:UIControlStateNormal];
        backButton.tag = kNavigationItemAlignment_HL_VC;
        [backButton addTarget:self
                       action:@selector(defaultBackButtonItemAction:)
             forControlEvents:UIControlEventTouchUpInside];
        _defaultBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        _defaultBackButtonItem.style = UIBarButtonItemStylePlain;

    }

    return _defaultBackButtonItem;
}

- (UIBarButtonItem *)defaultRefreshButtonItem
{
    if (!_defaultRefreshButtonItem)
    {
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.frame = CGRectMake(0.0, 0.0, self.navigationBarHeight, self.navigationBarHeight);
        [backButton setImage:[UIImage imageNamed:@"navigationbar_refresh_icon"]
                    forState:UIControlStateNormal];
        backButton.tag = kNavigationItemAlignment_HR_VC;
        [backButton addTarget:self
                       action:@selector(refreshData)
             forControlEvents:UIControlEventTouchUpInside];
        _defaultRefreshButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        _defaultRefreshButtonItem.style = UIBarButtonItemStylePlain;

    }

    return _defaultRefreshButtonItem;
}


- (NavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        
        _navigationBar = [[NavigationBar alloc] initWithFrame:CGRectMake(0,
                                                                         0,
                                                                         [UIScreen mainScreen].bounds.size.width,
                                                                         self.navigationBarHeight)];
        _navigationBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
    }
    return _navigationBar;
    
}
#pragma mark NavigationBar & TabBar & ToolBar

- (TabBarItem *)customTabBarItem
{
    if (!_customTabBarItem)
    {
        TabBarItem *tabBarItem = [[TabBarItem alloc] init];
        self.customTabBarItem = tabBarItem;
    }
    
    return _customTabBarItem;
}

- (void)setCustomTabBarItem:(TabBarItem *)customTabBarItem
{
    _customTabBarItem = customTabBarItem;
}


- (void)setupNavigationBar
{
    if (self.navigationBar.superview == nil)
    {
        [self.view addSubview:_navigationBar];
        [_navigationBar pushNavigationItem:self.navigationItem
                                  animated:NO];
    }
    
    [self.navigationBar performSelectorOnMainThread:@selector(useCustomBackgroundWithColor:)
                                         withObject:[UIColor colorWithHexString:@"83ccc8"]
                                      waitUntilDone:YES];
    [self.navigationBar performSelectorOnMainThread:@selector(setCustomShadowImage:)
                                         withObject:[UIImage createImageWithColor:[UIColor colorWithHexString:kNavigationBarShadowColor]]
                                      waitUntilDone:YES];
    [self.view addSubview:self.navigationBar];
}

#pragma mark - BaseViewDelegate

- (void)viewDidAddSubview:(UIView *)view
{
    if (self.hasNavigationBar &&
        self.navigationBar)
    {
        [self.view bringSubviewToFront:self.navigationBar];
    }
	[self.view bringSubviewToFront:self.coverView];


}

- (void)viewDidBringSubviewToFront:(UIView *)view
{
    if (self.hasNavigationBar && self.navigationBar)
    {
        [(BaseView *) self.view suppressDelegateForAction:^{
            [self.view bringSubviewToFront:self.navigationBar];
        }];
    }

}


#pragma mark -
#pragma mark - 是否 支持当前navigationController的左右滑动
/**
*  是否 支持当前navigationController的左右滑动
*/
- (BOOL)                   navigationController:(NavigationController *)navigationController
shouldNavigateInteractiveGestureRecognizerBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return NO;
}




#pragma mark -
#pragma mark - common methord
- (void)defaultBackButtonItemAction:(UIButton *)sender
{
    if (self.navigationController &&
        [self.navigationController.viewControllers count] > 1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}



- (void)back
{
    if([self.navigationController.viewControllers count] == 1)
    {
        [self dismissViewControllerAnimated:YES
                                 completion:nil];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (CGRect)viewContentFrame
{
    return CGRectMake(0,
                      self.navigationBarHeight,
                      self.view.width,
                      self.view.height - self.navigationBarHeight - self.customTabViewController.tabBarHeight);
}


#pragma mark show tips

- (void)showErrorMessage:(NSString *)errorMessage
{
    
	if (self.progressTipView)
	{
		[self.progressTipView hide];
	}
    if ([errorMessage length] == 0)
    {
        [TipHandler showNetWorkFailedOnlyTextWithResponseStatus:404];
    }
    else
    {
        [TipHandler showFail:errorMessage];
    }
}

- (void)showAlertMessage:(NSString *)alertMessage
{
    [TipHandler showAlert:alertMessage];
    
}

- (void)showSucceedMessage:(NSString *)succedMessage
{
    if ([succedMessage length] == 0)
    {
        [TipHandler showNetWorkFailedOnlyTextWithResponseStatus:404];
    }
    else
    {
        [TipHandler showSuccess:succedMessage];
    }
}

- (void)showAlertTip:(NSString *)tip
{
    if ([tip length] == 0)
    {
        [TipHandler showNetWorkFailedOnlyTextWithResponseStatus:404];
    }
    else
    {
        [TipHandler showAlert:tip];
    }
    
}

- (void)showProgressHUDWithMessage:(NSString *)message
{
    self.progressTipView = [TipView showWaitTipWithTextAndIndicatorNoRespondToTouchByTipView:message];
}

- (void)showProgressHUDCompleteMessage:(NSString *)message
{
	if (self.progressTipView)
	{
		[self.progressTipView resetWithTitle:message type:TipType_success];
		[self.progressTipView  performSelector:@selector(hide) withObject:nil afterDelay:0.5];
	}
	else
	{
		[TipHandler showSuccess:message];
	}
}


- (void)showHandleDataDefaultMessage
{
	self.progressTipView = [TipView showWaitTipWithTextAndIndicatorNoRespondToTouchByTipView:kHandleDataDefaultMessage];
}

- (void)showHandleDataCompleteDefaultMessage
{	
	if (self.progressTipView)
	{
		[self.progressTipView resetWithTitle:kHandleDataCompleteDefaultMessage type:TipType_success];
		[self.progressTipView  performSelector:@selector(hide) withObject:nil afterDelay:0.5];
	}
	else
	{
		[TipHandler showSuccess:kHandleDataCompleteDefaultMessage];
	}
}

#pragma - other

- (void)requestDataFromNet
{
    //获取网络数据
}

- (void)refreshData
{

}

- (BOOL)isRefreshData
{
    return (self.pageIndex == 0);
}


- (void)setNavigationTitle:(NSString *)title
{
	UILabel* titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
	titleLab.font = [UIFont systemFontOfSize:18];
	[titleLab setBackgroundColor:[UIColor clearColor]];
	titleLab.textColor = [UIColor whiteColor];
	titleLab.textAlignment = NSTextAlignmentCenter;
	titleLab.tag = kNavigationItemAlignment_HC_VC;
	//[self.navigationController.navigationBar addSubview:titleLab];
	self.navigationItem.titleView=titleLab;
	
	titleLab.text = title;
	
}

- (BOOL)handleResponse:(BaseResponse *)response
{
    BOOL result = NO;
    
    if (response.success)
    {
        
    }
    else
    {
        if (response.httpResponseCode == kNetConnectionCode)
        {
            [self showAlertMessage: NetWork_NotReachable];
        }
        else
        {
            [self showAlertMessage: Data_Error];

        }
        
        result = NO;
    }
    
    return result;
}


@end
